import { createWebHistory, createRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import DingTalkCallback from "@/views/DingTalkCallback.vue";
import OAuthCallbackView from "@/views/OAuthCallbackView.vue";
import QQBindPhoneView from '../views/QQBindPhoneView.vue'
import QQCallbackView from '../views/QQCallbackView.vue'
import WeChat_callback from '../views/WeChat_callback.vue'
import GiteeCallbackView from '../views/GiteeCallbackView.vue'
import IdCardVerificationView from '../views/IdCardVerificationView.vue'

import UserProfileView from '../views/userProfile.vue'
import WorkoutPlanView from '../views/WorkoutPlanView.vue'

import UserProfileOneView from '../views/userProfile_one.vue'
import DietPlanGenerationAndShow from '../views/DietPlanGenerationAndShow.vue'
import HistoricalDietPlan from '../views/HistoricalDietPlan.vue'
import NutritionAnalysis from '../views/NutritionAnalysis.vue'

const routes = [
    {
        path: '/oauth-callback',
        name: 'oauth-callback',
        component: OAuthCallbackView,
        meta: { requiresAuth: false }
    },
    {
        path: '/dingtalk-callback',
        name: 'dingtalk-callback',
        component: DingTalkCallback,
        meta: { requiresAuth: false }
    },
    { 
        path: '/', 
        component: HomeView,
        meta: { requiresAuth: true }
    },
    { 
        path: '/login', 
        component: LoginView,
        meta: { requiresAuth: false }
    },
    { 
        path: '/bind-phone', 
        component: QQBindPhoneView,
        meta: { requiresAuth: false }
    },
    {
        path: '/qq-callback',
        component: QQCallbackView,
        meta: { requiresAuth: false }
    },
    {
        path: '/wechat-callback',
        component: WeChat_callback,
        meta: { requiresAuth: false }
    },
    {
        path: '/gitee-callback',
        component: GiteeCallbackView,
        meta: { requiresAuth: false }
    },
    {
        path: '/id-card-verification',
        component: IdCardVerificationView,
        meta: { requiresAuth: true }
    },

    {
        path: '/user-profile',
        component: UserProfileView,
        meta: { requiresAuth: true }
    },

    {
        path: '/workout-plan',
        component: WorkoutPlanView,
    },

    {
        path: '/user-profile-one',
        name: 'userProfileOneCurrent',
        component: UserProfileOneView,
        meta: { requiresAuth: true }
    },
    {
        path: '/diet-plan',
        name: 'dietPlan',
        component: DietPlanGenerationAndShow,
        meta: { requiresAuth: true }
    },
    {
        path: '/historical-diet-plan',
        name: 'historicalDietPlan',
        component: HistoricalDietPlan,
        meta: { requiresAuth: true }
    },
    {
        path: '/nutrition-analysis',
        name: 'nutritionAnalysis',
        component: NutritionAnalysis,
        meta: { requiresAuth: true }
    },
    // 重定向根路径到首页
    { 
        path: '/home', 
        redirect: '/'
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
    console.log('路由守卫 - 目标路径:', to.path)
    console.log('路由守卫 - 来源路径:', from.path)
    console.log('路由守卫 - 目标组件:', to.matched[0]?.components?.default?.name || '未知')
    
    const token = localStorage.getItem('token')
    console.log('路由守卫 - 当前token:', !!token)
    
    if (to.meta.requiresAuth) {
        // 需要登录的页面
        if (!token) {
            console.log('路由守卫 - 需要登录但无token，重定向到登录页')
            ElMessage.warning('请先登录')
            next('/login')
        } else {
            console.log('路由守卫 - 已登录，允许访问')
            next()
        }
    } else {
        // 不需要登录的页面（如登录页）
        if (token && to.path === '/login') {
            // 已登录用户访问登录页，重定向到首页
            console.log('路由守卫 - 已登录用户访问登录页，重定向到首页')
            next('/')
        } else {
            console.log('路由守卫 - 不需要登录的页面，允许访问')
            next()
        }
    }
})

export default router